package cn.danger.com.model.action;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.UpdateListener;
import cn.danger.com.model.listener.OnCommonListener;
import cn.danger.com.util.Check;
import cn.danger.com.util.Constants;
import cn.danger.com.util.MyNetManager;

/**
 * Created by 俊 on 2016/12/29.
 */
public class ModifyPasswordModelImpl implements ModifyPasswordModel {

    private Context context;

    public ModifyPasswordModelImpl(Context context) {
        this.context = context;
    }

    private String check(String origin_password, String new_password, String confirm_password) {
        if (TextUtils.isEmpty(origin_password)) {
            return Constants.ORIGIN_PASSWORD_IS_EMPTY;
        }
        if (TextUtils.isEmpty(new_password)) {
            return Constants.NEW_PASSWORD_IS_EMPTY;
        }
        if (new_password.length() < 6) {
            return Constants.NEW_PASSWORD_IS_NO_LESS_THAN_SIX;
        }
        if (TextUtils.isEmpty(confirm_password)) {
            return Constants.CONFIRM_PASSWORD_IS_EMPTY;
        }
        if (!new_password.equals(confirm_password)) {
            return Constants.CONFIRM_PASSWORD_IS_WRONG;
        }
        return Constants.IS_RIGHT;
    }

    @Override
    public void updatePassword(String origin_password, String new_password, String confirm_password, final OnCommonListener listener) {
        String check_result = check(origin_password, new_password, confirm_password);
        if (!check_result.equals(Constants.IS_RIGHT)) {
            listener.onError(check_result);
        } else {
            if (!new MyNetManager(context).isNetworkAvailable()) {
                listener.onError(Constants.NETWORK_IS_NOT_AVAILABLE);
            } else {
                BmobUser.updateCurrentUserPassword(origin_password, new_password, new UpdateListener() {
                    @Override
                    public void done(BmobException e) {
                        if (e == null) {
                            listener.onSuccess(null);
                        } else {
                            Log.i("danger", "code---->>" + e.getErrorCode());
                            if (Check.checkByCode(e.getErrorCode()) == null) {
                                listener.onError(Constants.FAIL_TO_UPDATE_PASSWORD);
                            } else {
                                listener.onError(Check.checkByCode(e.getErrorCode()));
                            }
                        }
                    }
                });
            }
        }
    }
}
